package Client.GUI;

import java.awt.Color;
import java.awt.Component;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.ArrayList;

import javax.imageio.ImageIO;
import javax.sql.rowset.serial.SerialException;
import javax.swing.ImageIcon;
import javax.swing.JFileChooser;
import javax.swing.JLabel;
import javax.swing.JButton;
import javax.swing.JOptionPane;
import javax.swing.JTable;
import javax.swing.JComboBox;
import javax.swing.ListSelectionModel;
import javax.swing.border.LineBorder;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;

import Server.DataBase.Lesson;
import Server.DataBase.SubmittedTask;
import Server.GUI.MyJTable;
import Server.Message.MessageGetFile;
import Server.Message.MessageGetSubmittedFile;
import Server.Message.MessageGetSubmittedTask;
import Server.Message.MessageGetSubmittedTaskReplay;
import Server.Message.MessageGetTaskId;
import Server.Message.MessageGetTaskIdReplay;
import Server.Message.MessageLessonReplay;
import Server.Message.MessageTeacherLesson;

import Client.logic.ClientIF;

public class GetSubmittedTaskPanel extends MyJPanel {
	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;

	private JButton btnDownload;
	private JComboBox comboBoxLesson, comboBoxTask;
	private Lesson lesson;
	private int taskId;
	private MyJTable table;
	private ArrayList<SubmittedTask> taskArray;
	private JFileChooser chooser;
	private String dir;
	
	public GetSubmittedTaskPanel(ClientIF client) {
		super(PanelType.GET_SUBMITTED_TASK_PANEL,client);
		setLayout(null);
		
		BufferedImage myPic;
		try {
			myPic = ImageIO.read(new File("images"+ File.separator+"get submitted task.jpg"));
		
			JLabel lblAddClass = new JLabel(new ImageIcon(myPic), JLabel.CENTER);
			lblAddClass.setBounds(0, 23, 559, 99);
			add(lblAddClass);
		
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		init();
	}
	
	public void init(){
		initBtn();
		initComboBox();
		initLabel();
		initTables();
		
		getClient().sendMsgToServer(new MessageTeacherLesson(getClient().getUser().getIdUser()));
		MessageLessonReplay msg = (MessageLessonReplay) getClient().getMessageFromServer();
		
		comboBoxLesson.addItem("Choose");
		for (Lesson lesson : msg.getArray())
			comboBoxLesson.addItem(lesson);
		comboBoxLesson.addActionListener(new LessonListener());
	}
	
	private void initLabel(){
		JLabel lblSubject = new JLabel("Lesson:");
		lblSubject.setBounds(31, 173, 56, 16);
		add(lblSubject);
		
		JLabel lblTaskNumber = new JLabel("task number:");
		lblTaskNumber.setBounds(253, 173, 81, 16);
		add(lblTaskNumber);
	}
	
	private void initComboBox(){
		comboBoxLesson = new JComboBox();
		comboBoxLesson.setBounds(81, 170, 162, 22);
		add(comboBoxLesson);
			
		comboBoxTask = new JComboBox();
		comboBoxTask.setEnabled(false);
		comboBoxTask.setBounds(334, 170, 173, 22);
		add(comboBoxTask);
	}

	private void initBtn(){
		btnDownload = new JButton("download");
		btnDownload.setEnabled(false);
		btnDownload.addActionListener(new FileChooser());
		btnDownload.setBounds(192, 437, 97, 25);
		add(btnDownload);
	}
	
	public void initTables(){
        table = new MyJTable();
        table.getTable().setFont(new Font("Tahoma", Font.PLAIN, 11));
        table.getTable().setAutoResizeMode(JTable.AUTO_RESIZE_LAST_COLUMN);
        table.setBounds(10, 232, 549, 179);
        table.getTable().getSelectionModel().addListSelectionListener(new ListSelectionListener() {
                public void valueChanged(ListSelectionEvent e) {
                        table.selectedRow = table.getTable().getSelectedRow();
                        btnDownload.setEnabled(true);
                }
        });
        table.getTable().setBounds(2, 31, 572, 302);
        table.setBorder(new LineBorder(new Color(0, 0, 0), 1, true));
        table.getTable().setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
        add(table); 
        
}
	
	private class LessonListener implements ActionListener{
		public void actionPerformed(ActionEvent event) {
			try{
				lesson = (Lesson) comboBoxLesson.getSelectedItem();	
			
				getClient().sendMsgToServer(new MessageGetTaskId(lesson));
				MessageGetTaskIdReplay msg = (MessageGetTaskIdReplay) getClient().getMessageFromServer();
				comboBoxTask.removeAllItems();
				taskArray = new ArrayList<SubmittedTask>();
				SubmitedTaskModel stm = new SubmitedTaskModel();
				stm.setArray(taskArray);
				table.setModel(stm);
				if (msg.getMaxid()!=0){
					comboBoxTask.addItem("Choose");
					for (int i=1; i<msg.getMaxid(); i++) comboBoxTask.addItem(i);
					comboBoxTask.setEnabled(true);
					btnDownload.setEnabled(false);
					comboBoxTask.addActionListener(new TaskListener());
				} 
			} catch (java.lang.Throwable t){}
		}
	}
	
	private class TaskListener implements ActionListener{
		public void actionPerformed(ActionEvent event) {
			try{
				taskId =  (Integer) comboBoxTask.getSelectedItem();
			
				getClient().sendMsgToServer(new MessageGetSubmittedTask(lesson.getIdLesson(), taskId));
				MessageGetSubmittedTaskReplay msg = (MessageGetSubmittedTaskReplay) getClient().getMessageFromServer();
			
				taskArray = msg.getArray();
				SubmitedTaskModel stm = new SubmitedTaskModel();
				stm.setArray(taskArray);
				table.setModel(stm);
			
				btnDownload.setEnabled(false);
			} catch (java.lang.Throwable t){}
		}
	}
	
	private class FileChooser implements ActionListener{
		public void actionPerformed(ActionEvent e) {
			chooser = new JFileChooser(); 
			chooser.setCurrentDirectory(new java.io.File("."));
			chooser.setDialogTitle("Choose Folder");
			chooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
		    //
		    // disable the "All files" option.
		    //
			chooser.setAcceptAllFileFilterUsed(false);
		    //    
		    if (chooser.showSaveDialog((Component) getClient()) == JFileChooser.APPROVE_OPTION){
		    	dir = chooser.getSelectedFile().getAbsolutePath();
		    	getClient().sendMsgToServer(new MessageGetSubmittedFile(taskId, lesson.getIdLesson(), 
		    			taskArray.get(table.getSelectedItem()).getStudent().getIdUser()));
			    MessageGetFile msg = (MessageGetFile) getClient().getMessageFromServer();  
			    try {
			    		// write the inputStream to a FileOutputStream
			    		OutputStream out = new FileOutputStream(new File(dir+File.separator+msg.getFile().getFileName()));
			    		out.write(msg.getFile().getBlob().getBytes(1, msg.getFile().getSize()));
			    		out.close();
			    		System.out.println("New file created!");
			    		JOptionPane.showMessageDialog((Component) getClient(), "Download complete");
			    	    } catch (IOException e1) {
			    		System.out.println(e1.getMessage());
			    	    } catch (SerialException e2) {
							e2.printStackTrace();
						}
			}
		}
	}
	
	@Override
	public MyJPanel pushPanel() {
		return new GetSubmittedTaskPanel(getClient());
	}
}
